﻿<%@ WebHandler Language="C#" CodeBehind="Controller.ashx.cs" Class="PUCIT.eFCS.Controller" %>

using System;
using System.Web;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web.SessionState;
using System.Net.Mail;
using System.Web.Configuration;
using Newtonsoft.Json;
using Newtonsoft;
using PUCIT.eFCS.Business;
using PUCIT.eFCS.Utility.Encryption;

public class Controller : IHttpHandler, IRequiresSessionState
{

    public void ProcessRequest(HttpContext context)
    {
        try
        {
            if (context.Request.QueryString["action"].Equals("InitiateCirculation"))
                InitiateCirculation(context);

            else if (context.Request.QueryString["action"].Equals("ViewFormTemplate"))
                ViewFormTemplate(context);

            else if (context.Request.QueryString["action"].Equals("ViewDetails"))
                ViewCirculationDetails(context);

            else if (context.Request.QueryString["action"].Equals("EditDetails"))
                EditCirculationDetails(context);

            else if (context.Request.QueryString["action"].Equals("GetFieldIdList"))
                GetFieldIdList(context);

            else if (context.Request.QueryString["action"].Equals("SaveSectionValues"))
                SaveSectionValues(context);

            else if (context.Request.QueryString["action"].Equals("GeneratePrintPreview"))
                GeneratePrintPreview(context);
        }
        catch (Exception) { }
    }

    bool IsTextArea(string htmlId)
    {
        if (htmlId.EndsWith("Explanation") || htmlId.EndsWith("Comments"))
            return true;

        return false;
    }

    string GetCompleteTag(string tag, string value, bool isReadOnly, bool isTextArea)
    {
        if (isReadOnly)
            tag += " readonly=readonly style='background-color:LightGray'";

        if (isTextArea)
        {
            tag += ">";

            if (value != null)
                tag += value;

            tag += "</textarea>";
        }
        else
        {
            if (value != null)
            {
                value = value.Replace("'", "&#39;"); // Handling single quotes 
                tag += (" value='" + value + "'");
            }

            tag += "/>";
        }

        return tag;
    }

    void ProcessFieldHtmlTags(HttpContext context, Document document, int userId)
    {
        foreach (Section section in document.DocumentSections)
        {
            if (userId == section.UserId)
            {
                context.Session["sectionId"] = section.SectionId; // sectionId (for section that is going to be filled) has been stored in the session to access its elements (by id) later

                foreach (Field field in section.SectionFields)
                {
                    if (field.FieldHtmlId.Equals("StdSemesterDDL"))
                    {
                        string username = (string)context.Session["username"];

                        if (username.StartsWith("B", true, null)) // BS (8 Semesters)
                        {
                            field.FieldHtml = "<select id=StdSemesterDDL name=StdSemesterDDL><option value=1st>1st</option><option value=2nd>2nd</option><option value=3rd>3rd</option><option value=4th>4th</option><option value=5th>5th</option><option value=6th>6th</option><option value=7th>7th</option><option value=8th>8th</option></select>";
                        }
                        else // MS (4 Semesters)
                        {
                            field.FieldHtml = "<select id=StdSemesterDDL name=StdSemesterDDL><option value=1st>1st</option><option value=2nd>2nd</option><option value=3rd>3rd</option><option value=4th>4th</option></select>";
                        }
                    }
                    else if (!field.FieldHtmlId.EndsWith("DDL") && !field.FieldHtmlId.EndsWith("RB"))
                    {
                        field.FieldHtml = GetCompleteTag(field.FieldHtml, field.FieldValue, false, IsTextArea(field.FieldHtmlId));
                    }
                }
            }
            else
            {
                foreach (Field field in section.SectionFields)
                {
                    if (field.FieldHtmlId.EndsWith("DDL") || field.FieldHtmlId.EndsWith("RB"))
                    {
                        field.FieldHtml = "<input type=text id=StdRollNo name=StdRollNo size=59 readonly=readonly style='background-color:LightGray' value='" + field.FieldValue + "' />";
                    }
                    else
                    {
                        field.FieldHtml = GetCompleteTag(field.FieldHtml, field.FieldValue, true, IsTextArea(field.FieldHtmlId));
                    }
                }
            }
        }
    }

    void ProcessTemplateFieldHtmlTags(HttpContext context, Document document)
    {
        foreach (Section section in document.DocumentSections)
        {
            foreach (Field field in section.SectionFields)
            {
                if (field.FieldHtmlId.Equals("StdSemesterDDL"))
                {
                    field.FieldHtml = "<select id=StdSemesterDDL name=StdSemesterDDL><option value=1st>1st</option><option value=2nd>2nd</option><option value=3rd>3rd</option><option value=4th>4th</option><option value=5th>5th</option><option value=6th>6th</option><option value=7th>7th</option><option value=8th>8th</option></select>";
                }

                if (field.FieldHtmlId.EndsWith("DDL")) // Drop Down List
                {
                    field.FieldHtml = "<select disabled='disabled' " + field.FieldHtml.Substring(8);
                }
                else if (field.FieldHtmlId.EndsWith("RB")) // Radio Button
                {
                    string[] htmlParts = field.FieldHtml.Split('/');
                    htmlParts[0] += "disabled='disabled'";
                    htmlParts[1] += "disabled='disabled'";

                    field.FieldHtml = htmlParts[0] + "/" + htmlParts[1] + "/" + htmlParts[2];
                }
                else
                {
                    field.FieldHtml = GetCompleteTag(field.FieldHtml, field.FieldValue, true, IsTextArea(field.FieldHtmlId));
                }
            }
        }
    }

    string GenerateCirculationForm(Document document)
    {
        string formHtml = "<h2>" + document.DocumentName + "</h2>";

        foreach (Section section in document.DocumentSections)
        {
            formHtml += ("<h3><u>" + section.SectionTitle + "</u></h3>");
            formHtml += "<table cellpadding=8>";
            foreach (Field field in section.SectionFields)
            {
                formHtml += ("<tr><td>" + field.FieldLabel + "</td><td>" + field.FieldHtml + "</td></tr>");
            }
            formHtml += "</table>";
        }
        return formHtml;
    }

    string GeneratePrintForm(Document document)
    {
        string formHtml = "<h2>" + document.DocumentName + "</h2>";


        foreach (Section section in document.DocumentSections)
        {
            formHtml += ("<h3><u>" + section.SectionTitle + "</u></h3>");
            formHtml += "<table cellpadding=8>";
            foreach (Field field in section.SectionFields)
            {
                formHtml += ("<tr><td>" + field.FieldLabel + "</td><td>" + field.FieldValue + "</td></tr>");
            }
            formHtml += "</table>";
        }
        return formHtml;
    }

    void SendEmailNotification(Circulation circulation)
    {
        try
        {
            MailMessage msg = new MailMessage();
            BusinessClass eFCS = new BusinessClass();
            NameValueCollection queryStringParameters = new NameValueCollection();
            int userId = eFCS.GetUserIdByUserName(circulation.CurrentStation);

            string toEmailAddress = eFCS.GetEmailByUserId(userId);

            msg.To.Add(toEmailAddress);
            msg.From = new MailAddress("esdprjct@gmail.com");
            msg.Subject = "eFCS Circulation " + circulation.CirculationId + " | " + circulation.CurrentStation;

            msg.IsBodyHtml = true;

            string body = "<html><body>";
            body += "<h2>Circulation Details</h2><table rules=all cellpadding=10><tr style='text-align:center'><th>Circulation Id</th><th>Form Type</th><th>Initiater</th><th>Submission Date</th><th>Submission Time</th><th>Progress</th><th>Current Station</th></tr>";
            body += ("<tr style='text-align:center'><td>" + circulation.CirculationId + "</td><td>" + eFCS.GetAbbreviation(circulation.Document.DocumentName) + "</td><td>" + circulation.Initiater + "</td><td>" + circulation.SubmissionDate.ToShortDateString() + "</td><td>" + circulation.SubmissionDate.ToShortTimeString() + "</td><td>" + circulation.Progress + "%</td><td>" + circulation.CurrentStation + "</td></tr></table>");

            body += GenerateCirculationForm(circulation.Document);

            queryStringParameters.Add("circulationId", circulation.CirculationId.ToString());
            queryStringParameters.Add("userId", userId.ToString());

            // Encrypt query string parameters
            string encryptedString = CryptoQueryStringHandler.EncryptQueryStrings(queryStringParameters, WebConfigurationManager.AppSettings["CryptoKey"]);

            if (circulation.Progress.Equals("100"))
            {
                body += "<br /><h3>Click <a href='~/ViewCirculationDetails.aspx?" + encryptedString + "'>Here</a> to Open</h3>";
            }
            else
            {
                body += "<br /><h3>Click <a href='~/EditCirculationDetails.aspx?" + encryptedString + "'>Here</a> to Open</h3>";
            }
            body += "</body></html>";

            msg.Body = body;

            SmtpClient smtpClient = new SmtpClient();


            // Home
            smtpClient.Host = "smtp.gmail.com";
            smtpClient.EnableSsl = true;
            smtpClient.Credentials = new System.Net.NetworkCredential("esdprjct", "esd12345");

            /*

            // PUCIT
            smtpClient.Host = "192.168.1.4";
            smtpClient.Port = 25;
            
            */

            smtpClient.Send(msg);
        }
        catch (Exception) { }
    }

    void ViewFormTemplate(HttpContext context)
    {
        try
        {
            context.Response.ContentType = "text/plain";

            string encryptedQueryStringPrameters = (string)context.Session["params"];

            context.Session.Remove("params");

            // Decrypt query strings parameters
            string cryptoKey = WebConfigurationManager.AppSettings["CryptoKey"];
            string decryptedQueryString = CryptoQueryStringHandler.DecryptQueryStrings(encryptedQueryStringPrameters, cryptoKey);

            string[] keyValuePair = decryptedQueryString.Split('='); // e.g. {documentId,15

            int documentId = int.Parse(keyValuePair[1]);

            BusinessClass eFCS = new BusinessClass();

            Document document = eFCS.GenerateFormTemplate(documentId);

            ProcessTemplateFieldHtmlTags(context, document);

            string response = GenerateCirculationForm(document);

            context.Response.Write(response);
        }
        catch (Exception) { context.Response.Write("<h1>Page not found!</h1>"); }
    }

    void InitiateCirculation(HttpContext context)
    {
        try
        {
            context.Response.ContentType = "text/plain";

            BusinessClass eFCS = new BusinessClass();
            int documentId = int.Parse(context.Request.QueryString["documentId"]);

            context.Session["documentId"] = documentId;

            Document document = eFCS.GenerateForm(documentId, -1, (int)context.Session["userId"]);

            ProcessFieldHtmlTags(context, document, (int)context.Session["userId"]);

            string response = GenerateCirculationForm(document);
            response += "<br /><input id='Button1' type='button' value='Submit' onclick='SaveSectionValues()'/>";

            context.Response.Write(response);
        }
        catch (Exception) { }
    }

    void ViewCirculationDetails(HttpContext context)
    {
        try
        {
            context.Response.ContentType = "text/plain";

            string encryptedQueryStringPrameters = (string)context.Session["params"];

            context.Session.Remove("params");

            // Decrypt query strings parameters
            string cryptoKey = WebConfigurationManager.AppSettings["CryptoKey"];
            string decryptedQueryString = CryptoQueryStringHandler.DecryptQueryStrings(encryptedQueryStringPrameters, cryptoKey);

            string[] keyValuePairs = decryptedQueryString.Split('&'); // e.g. {circulationId=15,userId=1)
            string[] keyValuePair = keyValuePairs[0].Split('='); // e.g. {circulationId,15

            int circulationId = int.Parse(keyValuePair[1]);

            BusinessClass eFCS = new BusinessClass();

            Circulation circulation = eFCS.GetCirculationDetails(circulationId, true, -1);

            ProcessFieldHtmlTags(context, circulation.Document, -1);

            string response = "<h2>Circulation Details</h2><table rules=all cellpadding=10><tr style='text-align:center'><th>Circulation Id</th><th>Form Type</th><th>Initiater</th><th>Submission Date</th><th>Submission Time</th><th>Progress</th><th>Current Station</th></tr>";

            response += ("<tr style='text-align:center'><td>" + circulation.CirculationId + "</td><td>" + eFCS.GetAbbreviation(circulation.Document.DocumentName) + " " + circulation.Document.DocumentVersion + "</td><td>" + circulation.Initiater + "</td><td>" + circulation.SubmissionDate.ToShortDateString() + "</td><td>" + circulation.SubmissionDate.ToLongTimeString() + "</td><td>" + circulation.Progress + "%</td><td>" + circulation.CurrentStation + "</td></tr></table>");
            response += "<br />";
            response += GenerateCirculationForm(circulation.Document);
            response += "<br />";
            response += "<br /><input id=" + circulation.CirculationId + " type='button' value='Print' onclick='javascript:getPrint(this.id)'/>";
            context.Response.Write(response);
        }
        catch (Exception)
        {
            context.Response.Write("<h1>Page not found!</h1>");
        }
    }

    void GeneratePrintPreview(HttpContext context)
    {
        try
        {
            context.Response.ContentType = "text/plain";

            BusinessClass eFCS = new BusinessClass();

            int circulationId = int.Parse(context.Request.QueryString["circulationId"]);

            Circulation circulation = eFCS.GetPrintPreview(circulationId);

            //ProcessFieldHtmlTags(context, circulation.Document, -1);

            string response = GeneratePrintForm(circulation.Document);
            response += "<br />";
            response += "<input type='button' value='Print' onclick='location.reload(true);window.print();'>";
            context.Response.Write(response);
        }
        catch (Exception) { }
    }

    void EditCirculationDetails(HttpContext context)
    {
        try
        {
            context.Response.ContentType = "text/plain";

            int userId = (int)context.Session["userId"];
            string response = "";

            string encryptedQueryStringPrameters = (string)context.Session["params"];

            context.Session.Remove("params");

            // Decrypt query strings parameters
            string cryptoKey = WebConfigurationManager.AppSettings["CryptoKey"];
            string decryptedQueryString = CryptoQueryStringHandler.DecryptQueryStrings(encryptedQueryStringPrameters, cryptoKey);

            string[] keyValuePairs = decryptedQueryString.Split('&'); // e.g. {circulationId=15,userId=2)

            string[] keyValuePair = keyValuePairs[0].Split('='); // e.g. {circulationId,15)

            BusinessClass eFCS = new BusinessClass();

            int circulationId = int.Parse(keyValuePair[1]);

            Circulation circulation = eFCS.GetCirculationDetails(circulationId, true, userId);

            if (circulation.CurrentStation.Equals((string)context.Session["username"]))
            {

                ProcessFieldHtmlTags(context, circulation.Document, userId);

                context.Session["circulationId"] = circulationId;
                context.Session["documentId"] = eFCS.GetCirculationDocumentId(circulationId);

                response += "<h2>Circulation Details</h2><table rules=all cellpadding=10><tr style='text-align:center'><th>Circulation Id</th><th>Form Type</th><th>Initiater</th><th>Submission Date</th><th>Submission Time</th><th>Progress</th><th>Current Station</th></tr>";

                response += ("<tr style='text-align:center'><td>" + circulation.CirculationId + "</td><td>" + eFCS.GetAbbreviation(circulation.Document.DocumentName) + " " + circulation.Document.DocumentVersion + "</td><td>" + circulation.Initiater + "</td><td>" + circulation.SubmissionDate.ToShortDateString() + "</td><td>" + circulation.SubmissionDate.ToLongTimeString() + "</td><td>" + circulation.Progress + "%</td><td>" + circulation.CurrentStation + "</td></tr></table>");

                response += GenerateCirculationForm(circulation.Document);

                response += "<br /><input id='Button1' type='button' value='Submit' onclick='SaveSectionValues()'/>";
            }
            else
            {
                NameValueCollection queryStringParameters = new NameValueCollection();

                queryStringParameters.Add("circulationId", circulation.CirculationId.ToString());

                // Encrypt query string parameters
                string encryptedString = CryptoQueryStringHandler.EncryptQueryStrings(queryStringParameters, WebConfigurationManager.AppSettings["CryptoKey"]);

                response += "<h1>You have already edited details of <a href='~/eFCS_Site/ViewStationUserCirculationDetails.aspx?" + encryptedString + "'>Circulation: " + circulation.CirculationId + "</a></h1>";
            }

            context.Response.Write(response);
        }
        catch (Exception)
        {
            context.Response.Write("<h1>Page not found!</h1>");
        }
    }

    void GetFieldIdList(HttpContext context)
    {
        try
        {
            context.Response.ContentType = "text/plain";

            BusinessClass eFCS = new BusinessClass();
            List<string> fieldHtmlIdList = eFCS.GetFieldHtmlIdList((int)context.Session["sectionId"]);

            string response = JsonConvert.SerializeObject(fieldHtmlIdList);
            context.Response.Write(response);
        }
        catch (Exception) { }
    }

    void SaveSectionValues(HttpContext context)
    {
        try
        {
            List<string> fieldValues = new List<string>();
            Circulation circulationDetails;

            fieldValues = JsonConvert.DeserializeObject<List<string>>(context.Request.QueryString["jsonText"]);

            BusinessClass eFCS = new BusinessClass();

            if (context.Session["params"] != null)
                context.Session.Remove("params");

            if (context.Session.Count == 4) // documentId, sectionId, userId, username
            {
                int circulationId = eFCS.SaveSectionValues((int)(context.Session["documentId"]), (int)(context.Session["sectionId"]), (int)(context.Session["userId"]), fieldValues);

                circulationDetails = eFCS.GetCirculationDetails(circulationId, true, -1);
                ProcessFieldHtmlTags(context, circulationDetails.Document, -1);

                SendEmailNotification(circulationDetails);

                context.Response.ContentType = "text/plain";

                context.Session.Remove("documentId");
                context.Session.Remove("sectionId");

                NameValueCollection queryStringParameters = new NameValueCollection();

                queryStringParameters.Add("circulationId", circulationId.ToString());

                // Encrypt query string parameters
                string encryptedString = CryptoQueryStringHandler.EncryptQueryStrings(queryStringParameters, WebConfigurationManager.AppSettings["CryptoKey"]);

                context.Response.Write("<h1>Successfully Saved!</h1><h1>Your Circulation Id is: <a href='~/eFCS_Site/ViewCirculationDetails.aspx?" + encryptedString + "'>" + circulationId + "</a></h1>");
            }

            else // (Count = 5) i.e. circulationId, documentId, sectionId, userId, username (Save section values of a station user)
            {
                int circulationId = (int)(context.Session["circulationId"]);

                eFCS.SaveStationUserSectionValues(circulationId, (int)(context.Session["documentId"]), (int)(context.Session["sectionId"]), (int)(context.Session["userId"]), fieldValues);

                circulationDetails = eFCS.GetCirculationDetails(circulationId, true, -1);
                ProcessFieldHtmlTags(context, circulationDetails.Document, -1);

                SendEmailNotification(circulationDetails);

                context.Response.ContentType = "text/plain";

                context.Session.Remove("circulationId");
                context.Session.Remove("documentId");
                context.Session.Remove("sectionId");

                context.Response.Write("<h1>Successfully Saved!</h1>");
            }
        }
        catch (Exception) { }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}